﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using eGov.SharePoint.MyPeeps.WebParts;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;

namespace eGov.SharePoint.MyPeeps.WebControls
{
    public partial class PublishedUpdatesUserControl : UserControl
    {
        private bool DateCategoryToday { get; set; }
        private bool DateCategoryYesterday { get; set; }
        private bool DateCategoryEarlier { get; set; }

        public int InitialFeedsCount { get; set; }
        protected FeedSource FeedsSource { get { return FeedSource.Published; } }
        public bool ViewMore { get; set; }
        public int ViewMoreCount { get; set; }

        public int FeedsCount
        {
            get
            {
                if (ViewState["feedsCount"] == null)
                    ViewState["feedsCount"] = this.InitialFeedsCount;
                return (int)ViewState["feedsCount"];
            }
            set
            {
                ViewState["feedsCount"] = value;
            }
        }
        protected bool HasMoreFeeds { get; set; }

        protected HtmlGenericControl eGov_TabbedControl;
        protected HtmlGenericControl contentFeeds;
        protected HtmlGenericControl contentInfo;
        protected HtmlGenericControl contentViewMore;
        protected HyperLink NavigateUrl;
        protected LinkButton linkShowMoreFeeds;
        protected ListView MyActivityFeedList;

        protected UpdatePanel UpdatePanel;
        protected ObjectDataSource myActivityFeedDataSource;
        protected Button btnTest;


        #region ULS Prep

        private SPDiagnosticsArea logArea;
        private SPDiagnosticsService logService = SPDiagnosticsService.Local;
        protected SPDiagnosticsArea LogArea
        {
            get
            {
                if (this.logArea == null)
                    this.logArea = new SPDiagnosticsArea("eGov.SharePoint.MyPeeps", new List<SPDiagnosticsCategory>
                    { 
                        new SPDiagnosticsCategory("PublishedUpdatesUserControl", TraceSeverity.High, EventSeverity.Error),
                        new SPDiagnosticsCategory("PublishedUpdatesUserControl", TraceSeverity.Verbose, EventSeverity.Information) 
                    });
                return this.logArea;
            }
        }
        protected SPDiagnosticsCategory logCategory_Error
        {
            // Indexing if used starts from 1
            get { return this.LogArea.Categories[1]; }
        }
        protected SPDiagnosticsCategory logCategory_Information
        {
            // Indexing if used starts from 1
            get { return this.LogArea.Categories[2]; }
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {

                if (this.IsPostBack == false)
                {
                    this.FeedsCount = InitialFeedsCount;
                }
            }
            catch (Exception ex)
            {

                Response.Write(ex.ToString());
            }
        }

        protected void btnTest_Click(object sender, EventArgs e)
        {
            myActivityFeedDataSource.Select();
            MyActivityFeedList.DataBind();
        }

        protected void myActivityFeedDataSource_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            e.InputParameters[0] = this.FeedsSource;
            e.InputParameters[1] = this.FeedsCount;
        }

        protected void myActivityFeedDataSource_Selected(object sender, ObjectDataSourceStatusEventArgs e)
        {
            if (e.Exception != null)
            {
                logService.WriteTrace(100, logCategory_Error, TraceSeverity.High,
                          String.Format("Loading published activity feeds failed. Exception message: {0} \r\n Stack Trace: \r\n {1}", new object[] { e.Exception.Message, e.Exception.StackTrace }), null);

                this.contentInfo.Visible = true;
                this.contentFeeds.Visible = false;
                this.contentViewMore.Visible = false;
                e.ExceptionHandled = true;
                return;
            }

            this.HasMoreFeeds = (bool)e.OutputParameters["HasMoreFeeds"];

            if (this.HasMoreFeeds == false)
            {
                this.linkShowMoreFeeds.Text = "No more feeds";
                this.linkShowMoreFeeds.Enabled = false;
            }
            else
            {
                this.linkShowMoreFeeds.Text = "More Feeds";
                this.linkShowMoreFeeds.Enabled = true;
            }

            if (e.ReturnValue != null && e.ReturnValue is ICollection && (e.ReturnValue as ICollection).Count > 0)
            {
                this.contentFeeds.Visible = true;
                this.contentInfo.Visible = false;

                if (this.ViewMore) this.contentViewMore.Visible = true;
                else this.contentViewMore.Visible = false;
            }
            else
            {
                this.contentInfo.Visible = true;
                this.contentFeeds.Visible = false;
                this.contentViewMore.Visible = false;
            }
        }

        protected void MyActivityFeedList_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            // Set date category if first for that time span
            Label categoryLabel = e.Item.FindControl("feedDateCategory") as Label;
            ActivityFeedEntity dataItem = (e.Item as ListViewDataItem).DataItem as ActivityFeedEntity;

            bool flagLabelSet = false;
            if (dataItem != null && dataItem.PublishedDate < DateTime.Now)
            {
                if (dataItem.PublishedDate.DayOfYear == DateTime.Now.DayOfYear && dataItem.PublishedDate.Year == DateTime.Now.Year)
                    if (flagLabelSet == false && this.DateCategoryToday == false)
                    {
                        categoryLabel.Text = "Today";
                        this.DateCategoryToday = true;
                        flagLabelSet = true;
                    }
                if (dataItem.PublishedDate.DayOfYear + 1 == DateTime.Now.DayOfYear && dataItem.PublishedDate.Year == DateTime.Now.Year)
                    if (flagLabelSet == false && this.DateCategoryYesterday == false)
                    {
                        categoryLabel.Text = "Yesterday";
                        this.DateCategoryYesterday = true;
                        flagLabelSet = true;
                    }
                if (dataItem.PublishedDate.DayOfYear < DateTime.Now.DayOfYear)
                    if (flagLabelSet == false && this.DateCategoryEarlier == false)
                    {
                        categoryLabel.Text = "Earlier";
                        this.DateCategoryEarlier = true;
                        flagLabelSet = true;
                    }
            }

        }

        protected void linkShowMoreFeeds_Click(object sender, EventArgs e)
        {
            this.FeedsCount += this.ViewMoreCount;
            this.MyActivityFeedList.DataBind();
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            string scriptKey = "MyPublishedUpdatesScript";

            if (!Page.ClientScript.IsStartupScriptRegistered(scriptKey))
            {
                string scriptBlock =
                   @"<script language='javascript'>

                  function ReloadUpdates()
                    {
                            var prm = Sys.WebForms.PageRequestManager.getInstance();
                            prm._doPostBack('UpdatePanel', '');
                         
                    }
                </script>";

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), scriptKey, scriptBlock);
            }

        }
    }
}